<template>
  <div class="personal-center">
    <!-- 顶栏 -->
    <TopBar />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 菜单 -->
      <MenuLine />

      <!-- 个人信息 -->
      <el-card class="info-card">
        <template #header>
          <div class="card-header">
            <h2>个人信息</h2>
          </div>
        </template>
        <el-form :model="userInfo" label-width="100px" disabled>
          <el-form-item label="用户名">
            <el-input v-model="userInfo.username" disabled />
          </el-form-item>
          <el-form-item label="真实姓名">
            <el-input v-model="userInfo.realName" disabled />
          </el-form-item>
          <el-form-item label="角色">
            <el-input v-model="userInfo.role" disabled />
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 修改密码 -->
      <el-card class="password-card">
        <template #header>
          <div class="card-header">
            <h2>修改密码</h2>
          </div>
        </template>
        <el-form
          :model="passwordForm"
          :rules="passwordRules"
          ref="passwordFormRef"
          label-width="100px"
        >
          <el-form-item label="旧密码" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              show-password
              placeholder="请输入旧密码"
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              show-password
              placeholder="请输入新密码"
            />
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              show-password
              placeholder="请再次输入新密码"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitPasswordForm">提交</el-button>
            <el-button @click="resetPasswordForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/user';
import axios from '@/plugins/axios';
import TopBar from '@/components/TopBar.vue'; // 新增
import MenuLine from '@/components/MenuLine.vue'; // 新增

const userStore = useUserStore();
const router = useRouter();

// 个人信息
const userInfo = ref({
  username: '',
  realName: '',
  role: '',
});

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

const passwordFormRef = ref<FormInstance>();

// 密码校验规则
const passwordRules = ref<FormRules>({
  oldPassword: [
    { required: true, message: '请输入旧密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' },
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.value.newPassword) {
          callback(new Error('两次输入的密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur',
    },
  ],
});

// 加载个人信息
const fetchUserInfo = async () => {
  if (!userStore.user?.id) {
    ElMessage.error('用户未登录');
    router.push('/login');
    return;
  }
  try {
    const userData = await userStore.fetchUserInfo(userStore.user.id);
    userInfo.value = {
      username: userData.username || '未知',
      realName: userData.realName || '未设置',
      role: userData.role || 'EMPLOYEE',
    };
  } catch (error) {
    ElMessage.error('加载个人信息失败');
  }
};

// 提交修改密码
const submitPasswordForm = async () => {
  if (!passwordFormRef.value) return;
  passwordFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!userStore.user?.id) {
        ElMessage.error('用户未登录');
        router.push('/login');
        return;
      }
      try {
        const response = await axios.put('/api/users/password', {
          id: userStore.user.id,
          password: passwordForm.value.newPassword,
        });
        if (response.data.code === 200) {
          ElMessage.success('密码修改成功，请重新登录');
          userStore.logout();
          router.push('/login');
        } else {
          ElMessage.error(response.data.message || '密码修改失败');
        }
      } catch (error) {
        ElMessage.error('密码修改失败');
      }
    }
  });
};

// 重置密码表单
const resetPasswordForm = () => {
  if (!passwordFormRef.value) return;
  passwordFormRef.value.resetFields();
};

// 初始化加载
onMounted(() => {
  fetchUserInfo();
});
</script>

<style scoped>
.personal-center {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content {
  padding-top: 60px; /* 留出顶栏高度 */
  width: 80%;
  margin: 0 auto;
  padding-bottom: 60px; /* 底部留白 */
}

.info-card,
.password-card {
  margin: 20px 0; /* 调整为上下 margin */
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  background-color: #ffffff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.el-form {
  padding: 20px;
}

.el-button {
  margin-right: 10px;
}
</style>